new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Dingtalk_Message_SerialNumber: '',
                Dingtalk_Message_Name: '',
                Template_SerialNumber: '',
                Msg_Param: '',
                App_ID: '',
                Enterprise_Info_SerialNumber: $.cookie('token'),
                Children: {
                    dingtalk_message_userids: []
                },
            },
            rules: {
                Dingtalk_Message_Name: [{ required: true, message: '请输入消息推送实例名称', trigger: 'blur' }],
                Template_SerialNumber:[{ required: true, message: '请选择消息推送模板', trigger: 'change' }]
            },
            template: [],//复合模版
            userids: [],//推送人员
            loading: false,
            Msg_Key: '',//模板类型
            Msg_Param: {},//模板预览
            User_Id: [],
        }
    },
    mounted() {
        const Dingtalk_Message_SerialNumber = sessionStorage.getItem("Dingtalk_Message_SerialNumber");
        this.getData(Dingtalk_Message_SerialNumber);
    },
    methods: {
        getData(Primary_Key) {
            const that = this;
            $.ajax({
                url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie('token'),
                type: 'POST',
                data: {
                    Primary_Key,
                    JSONObject: JSON.stringify({ dingtalk_message_config: { dingtalk_message_userids: {} } }),
                    Row_Status: JSON.stringify({ dingtalk_message_userids: '' })
                },
                success: function (res) {
                    if (res.dingtalk_message_config.length > 0) {
                        that.form = res.dingtalk_message_config[0];
                        that.change(that.form.Template_SerialNumber)
                        that.form.Children.dingtalk_message_userids.forEach(item => {
                            if (item.Row_Status == '0') {
                                that.User_Id.push(item.User_ID)
                            }
                        })
                    }
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
            $.ajax({
                type: 'POST',
                url: DomainName + "/getInquiryAction?token=" + $.cookie('token'),
                data: {
                    Data: "dingtalk_message_template",
                },
                success: function (data) {
                    if (data.length > 0) {
                        that.template = data;
                    }
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });
            $.ajax({
                type: 'POST',
                url: DomainName + "/getInquiryAction?token=" + $.cookie('token'),
                data: {
                    Data: "dingtalk_userids_info",
                },
                success: function (data) {
                    if (data.length > 0) {
                        that.userids = data;
                    }
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });
        },
        change(e) {//选择模板
            if (e) {
                let obj = this.template.filter(i => i.Template_SerialNumber == e)[0];
                this.Msg_Key = obj.Msg_Key
                this.Msg_Param = obj.Msg_Param;
            } else {
                this.Msg_Key = '';
                this.Msg_Param = {};
            }
        },
        submitForm(formName) {
            let _this = this
            if (this.User_Id.length == 0) {
                this.$message.error("发送成员不能为空")
                return
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.loading = true;
                    _this.config_dingtalk_message_config();
                    const { add, modify } = _this.deal()
                    let data = {}
                    if (add == null) {
                        data = { Data: JSON.stringify({ Modify: { dingtalk_message_config: [modify] } }), Operation_Name: '修改消息推送实例' }
                    } else {
                        data = { Data: JSON.stringify({ Modify: { dingtalk_message_config: [modify] }, Add: { dingtalk_message_config: [add], } }), Operation_Name: '修改消息推送实例' }
                    }
                    $.ajax({
                        url: DomainName + '/getEditAction?token=' + $.cookie('token'),
                        type: 'POST',
                        data,
                        success: function (res) {
                            if (res.Status === 'success') {
                                _this.$message.success("修改成功")
                                window.history.go(-1)
                            } else {
                                _this.$message.error("提交失败，请稍后再试")
                            }
                        },
                        error: function () {
                            _this.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            _this.loading = false
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    return false;
                }
            });
        },
        config_dingtalk_message_config() {//提交前的整理数组
            this.form.Msg_Param = JSON.stringify(this.Msg_Param);
            //将选中的新数据添加到数组中
            this.User_Id.forEach(User_ID => {
                if (!this.form.Children.dingtalk_message_userids.some(item => item.User_ID == User_ID)) {//判断数组中是否含有这个值
                    this.form.Children.dingtalk_message_userids.push({
                        Message_Userids_SerialNumber: '',
                        Dingtalk_Message_SerialNumber: this.form.Dingtalk_Message_SerialNumber,
                        User_ID
                    })
                }else if (this.form.Children.dingtalk_message_userids.some(item => item.User_ID == User_ID && item.Row_Status == '1')) {
                    this.form.Children.dingtalk_message_userids.filter(item => item.User_ID == User_ID && item.Row_Status == '1')[0].Row_Status = '0'
                }
            })
            //将没被选中的数组状态改为0
            this.form.Children.dingtalk_message_userids.forEach(item => {
                if (!this.User_Id.some(i => i == item.User_ID)) {
                    item.Row_Status = '1'
                }
            })
        },
        deal() {
            const add = deepClone(this.form)
            const modify = deepClone(this.form)
            let add_dingtalk_message_userids = [], modify_dingtalk_message_userids = []

            for (const i in modify.Children.dingtalk_message_userids) {
                const obj = modify.Children.dingtalk_message_userids[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_dingtalk_message_userids.push(obj)
                } else {
                    modify_dingtalk_message_userids.push(obj)
                }
            }

            add.Children.dingtalk_message_userids = add_dingtalk_message_userids
            modify.Children.dingtalk_message_userids = modify_dingtalk_message_userids

            if (add_dingtalk_message_userids.length == 0) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
})